<!-- src/views/pages/MaterialInboundManage.vue -->
<template>
  <div class="material-inbound-manage">
    <!-- 顶栏 -->
    <TopBar />

    <!-- 内容区域 -->
    <div class="content">
      <!-- 菜单 -->
      <MenuLine />

      <!-- 操作栏 -->
      <div class="operation-bar">
        <el-button type="primary" @click="openAddDialog">添加入库记录</el-button>
      </div>

      <!-- 入库记录列表 -->
      <el-table :data="inboundList" style="width: 100%" border v-loading="loading">
        <el-table-column prop="id" label="ID" width="100" />
        <el-table-column prop="inboundNumber" label="入库编号" width="150" />
        <el-table-column prop="materialName" label="物资名称" />
        <el-table-column prop="quantity" label="数量" width="120" />
        <el-table-column prop="status" label="状态" width="120" />
        <el-table-column prop="operatorName" label="操作人" width="150" />
        <el-table-column prop="inboundTime" label="入库时间" width="250" />
        <el-table-column prop="expirationDate" label="保质期" width="150" />
        <el-table-column label="操作" width="300">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="openEditDialog(row)">编辑</el-button>
            <el-button type="danger" size="small" @click="deleteInbound(row.id)">删除</el-button>
            <el-button
              :disabled="!isPendingStatus(row.status)"
              type="success"
              size="small"
              @click="openReviewDialog(row)"
            >
              审核
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 添加/编辑弹窗 -->
      <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        width="30%"
        @close="resetForm"
      >
        <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
          <el-form-item
            v-for="field in inboundFields"
            :key="field.key"
            :label="field.label"
            :prop="field.key"
          >
            <el-input
              v-if="field.type === 'text'"
              v-model="form[field.key]"
              :placeholder="field.placeholder"
              :maxlength="field.maxLength"
            />
            <el-input
              v-if="field.type === 'number'"
              v-model.number="form[field.key]"
              type="number"
              :placeholder="field.placeholder"
              :min="1"
            />
            <el-select
              v-else-if="field.type === 'select'"
              v-model="form[field.key]"
              :placeholder="field.placeholder"
              style="width: 100%"
              :disabled="!field.options || !field.options.length"
            >
              <el-option
                v-for="option in field.options"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
              <el-option v-if="!field.options || !field.options.length" disabled label="无可用选项" :value="''" />
            </el-select>
            <el-date-picker
              v-else-if="field.type === 'date'"
              v-model="form[field.key]"
              type="date"
              :placeholder="field.placeholder"
              style="width: 100%"
              :disabled-date="disablePastDates"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :disabled="!materialOptions.length">确定</el-button>
        </template>
      </el-dialog>

      <!-- 审核弹窗 -->
      <el-dialog
        title="审核入库记录"
        v-model="reviewDialogVisible"
        width="30%"
        @close="resetReviewForm"
      >
        <el-form :model="reviewForm" :rules="reviewRules" ref="reviewFormRef" label-width="80px">
          <el-form-item label="状态" prop="status">
            <el-select v-model="reviewForm.status" placeholder="请选择审核状态" style="width: 100%">
              <el-option label="通过" value="通过" />
              <el-option label="拒绝" value="拒绝" />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="reviewDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitReview">确定</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus';
import { useMaterialInboundStore, inboundFields, type MaterialInbound } from '@/stores/inbound';
import { useMaterialStore } from '@/stores/material';
import { useUserStore } from '@/stores/user';
import TopBar from '@/components/TopBar.vue';
import MenuLine from '@/components/MenuLine.vue';

// 入库记录、物资和用户 store
const inboundStore = useMaterialInboundStore();
const materialStore = useMaterialStore();
const userStore = useUserStore();
const inboundList = ref<MaterialInbound[]>([]);
const loading = ref(false);

// 物资和用户选项
const materialOptions = ref<{ value: string; label: string }[]>([]);
const userOptions = ref<{ value: string; label: string }[]>([]);

// 判断当前用户是否为管理员
const isAdmin = computed(() => {
  const isManager = userStore.user?.role === 'MANAGER';
  return isManager;
});

// 判断状态是否为“待审核”
const isPendingStatus = (status: string) => {
  const isPending = status === '待审核' || status === 'PENDING';
  return isPending;
};

// 动态更新 inboundFields 的选项
inboundFields.find(f => f.key === 'materialId')!.options = materialOptions.value;
inboundFields.find(f => f.key === 'operatorId')!.options = userOptions.value;

// 弹窗控制
const dialogVisible = ref(false);
const dialogTitle = ref('添加入库记录');
const isEdit = ref(false);
const form = ref<MaterialInbound>({
  id: 0,
  inboundNumber: '',
  materialId: '',
  materialName: '',
  quantity: 0,
  status: '待审核',
  reviewerId: null,
  operatorId: '',
  operatorName: '',
  inboundTime: '',
  expirationDate: '',
});
const formRef = ref<FormInstance>();

// 审核弹窗
const reviewDialogVisible = ref(false);
const reviewForm = ref({
  id: 0,
  status: '',
  reviewerId: userStore.user?.id || 0,
});
const reviewFormRef = ref<FormInstance>();
const reviewRules = ref<FormRules>({
  status: [{ required: true, message: '请选择审核状态', trigger: 'change' }],
});

// 表单校验规则
const rules = ref<FormRules>({
  inboundNumber: [
    { required: true, message: '请输入入库编号', trigger: 'blur' },
    { pattern: /^IN\d{3}$/, message: '入库编号格式为 IN+3位数字（如 IN001）', trigger: 'blur' },
  ],
  materialId: [
    { required: true, message: '请选择物资', trigger: 'change' },
  ],
  quantity: [
    { required: true, message: '请输入数量', trigger: 'blur' },
    { type: 'number', min: 1, message: '数量必须大于0', trigger: 'blur' },
  ],
  operatorId: [
    { required: true, message: '请选择操作人', trigger: 'change' },
  ],
  expirationDate: [
    { required: true, message: '请选择保质期', trigger: 'change' },
  ],
});

// 禁用过去日期
const disablePastDates = (time: Date) => {
  return time.getTime() < Date.now() - 24 * 60 * 60 * 1000;
};

// 获取物资选项
const fetchMaterials = async () => {
  try {
    const materials = await materialStore.fetchMaterials();
    materialOptions.value = materials.map(material => ({
      value: material.id.toString(),
      label: material.name,
    }));
    inboundFields.find(f => f.key === 'materialId')!.options = materialOptions.value;
    console.log('物资选项:', materialOptions.value);
  } catch (error) {
    ElMessage.error('获取物资列表失败');
    console.error('物资加载失败:', error);
  }
};

// 获取用户选项
const fetchUsers = async () => {
  try {
    const users = await userStore.fetchUsers();
    userOptions.value = users.map(user => ({
      value: user.id.toString(),
      label: user.realName,
    }));
    inboundFields.find(f => f.key === 'operatorId')!.options = userOptions.value;
    console.log('用户选项:', userOptions.value);
  } catch (error) {
    ElMessage.error('获取用户列表失败');
    console.error('用户加载失败:', error);
  }
};

// 获取入库记录列表并检查过期
const fetchInbounds = async () => {
  loading.value = true;
  try {
    const result = await inboundStore.fetchInbounds();
    console.log('后端入库记录:', result); // 调试：记录原始数据
    inboundList.value = result.map(inbound => {
      const materialIdStr = inbound.materialId != null ? inbound.materialId.toString() : '';
      const operatorIdStr = inbound.operatorId != null ? inbound.operatorId.toString() : '';
      const materialName = materialOptions.value.find(opt => opt.value === materialIdStr)?.label || '未知物资';
      const operatorName = userOptions.value.find(opt => opt.value === operatorIdStr)?.label || '未知用户';
      // 映射状态，兼容后端返回的英文值
      const status = inbound.status === 'PENDING' ? '待审核' : inbound.status === 'APPROVED' ? '通过' : inbound.status === 'REJECTED' ? '拒绝' : inbound.status;
      return {
        ...inbound,
        status, // 更新状态
        materialName,
        operatorName,
        inboundTime: inbound.inboundTime ? new Date(inbound.inboundTime).toLocaleString() : '',
        expirationDate: inbound.expirationDate ? new Date(inbound.expirationDate).toLocaleDateString() : '',
      };
    });
    checkExpiringMaterials();
    console.log('入库记录列表:', inboundList.value);
  } catch (error: any) {
    const errorMessage = error.response?.data?.message || '获取入库记录列表失败';
    ElMessage.error(errorMessage);
    console.error('入库记录加载失败:', error, error.response?.data);
  } finally {
    loading.value = false;
  }
};

// 检查即将过期的物资
const checkExpiringMaterials = () => {
  const today = new Date();
  const warningDays = 30; // 30天内即将过期
  inboundList.value.forEach(inbound => {
    if (inbound.expirationDate) {
      const expDate = new Date(inbound.expirationDate);
      const daysUntilExpiry = Math.ceil((expDate.getTime() - today.getTime()) / (1000 * 60 * 60 * 24));
      if (daysUntilExpiry <= warningDays && daysUntilExpiry >= 0) {
        ElMessage.warning(`物资 ${inbound.materialName}（入库编号：${inbound.inboundNumber}）将在 ${daysUntilExpiry} 天后过期！`);
      }
    }
  });
};

// 打开添加弹窗
const openAddDialog = async () => {
  isEdit.value = false;
  dialogTitle.value = '添加入库记录';
  await fetchMaterials();
  await fetchUsers();
  form.value = {
    id: 0,
    inboundNumber: '',
    materialId: materialOptions.value[0]?.value || '',
    materialName: materialOptions.value[0]?.label || '',
    quantity: 0,
    status: '待审核',
    reviewerId: null,
    operatorId: userStore.user?.id.toString() || userOptions.value[0]?.value || '',
    operatorName: userStore.user?.realName || userOptions.value[0]?.label || '',
    inboundTime: '',
    expirationDate: '',
  };
  dialogVisible.value = true;
};

// 打开编辑弹窗
const openEditDialog = async (row: MaterialInbound) => {
  isEdit.value = true;
  dialogTitle.value = '编辑入库记录';
  await fetchMaterials();
  await fetchUsers();
  form.value = {
    ...row,
    materialId: row.materialId?.toString() || '',
    operatorId: row.operatorId?.toString() || '',
    expirationDate: row.expirationDate ? new Date(row.expirationDate) : '',
  };
  dialogVisible.value = true;
};

// 打开审核弹窗
const openReviewDialog = (row: MaterialInbound) => {
  reviewForm.value = {
    id: row.id,
    status: '',
    reviewerId: userStore.user?.id || 0,
  };
  console.log('打开审核弹窗:', reviewForm.value); // 调试：检查审核表单
  reviewDialogVisible.value = true;
};

// 提交表单（添加或编辑）
const submitForm = async () => {
  if (!formRef.value) return;
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const payload = {
          id: form.value.id,
          inboundNumber: form.value.inboundNumber,
          materialId: parseInt(form.value.materialId),
          quantity: form.value.quantity,
          operatorId: parseInt(form.value.operatorId),
          expirationDate: form.value.expirationDate
            ? new Date(form.value.expirationDate).toISOString().split('T')[0]
            : null,
        };
        console.log('提交入库记录:', payload); // 调试：记录请求数据
        if (isEdit.value) {
          await inboundStore.updateInbound(payload);
          ElMessage.success('编辑入库记录成功');
        } else {
          await inboundStore.createInbound(payload);
          ElMessage.success('添加入库记录成功');
        }
        dialogVisible.value = false;
        await fetchInbounds();
      } catch (error: any) {
        const errorMessage = error.response?.data?.message || (isEdit.value ? '编辑入库记录失败' : '添加入库记录失败');
        ElMessage.error(errorMessage);
        console.error('提交失败:', error, error.response?.data);
      }
    }
  });
};

// 提交审核
const submitReview = async () => {
  if (!reviewFormRef.value) return;
  reviewFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        console.log('提交审核:', reviewForm.value); // 调试：记录审核数据
        await inboundStore.reviewInbound(reviewForm.value);
        ElMessage.success('审核入库记录成功');
        reviewDialogVisible.value = false;
        await fetchInbounds();
      } catch (error: any) {
        const errorMessage = error.response?.data?.message || '审核入库记录失败';
        ElMessage.error(errorMessage);
        console.error('审核失败:', error, error.response?.data);
      }
    }
  });
};

// 删除入库记录
const deleteInbound = async (id: number) => {
  ElMessageBox.confirm('确定删除该入库记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        await inboundStore.deleteInbound(id);
        ElMessage.success('删除入库记录成功');
        await fetchInbounds();
      } catch (error: any) {
        const errorMessage = error.response?.data?.message || '删除入库记录失败';
        ElMessage.error(errorMessage);
        console.error('删除失败:', error, error.response?.data);
      }
    })
    .catch(() => {
      ElMessage.info('取消删除');
    });
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  form.value = {
    id: 0,
    inboundNumber: '',
    materialId: '',
    materialName: '',
    quantity: 0,
    status: '待审核',
    reviewerId: null,
    operatorId: '',
    operatorName: '',
    inboundTime: '',
    expirationDate: '',
  };
};

// 重置审核表单
const resetReviewForm = () => {
  if (reviewFormRef.value) {
    reviewFormRef.value.resetFields();
  }
  reviewForm.value = { id: 0, status: '', reviewerId: userStore.user?.id || 0 };
};

// 初始化加载
onMounted(async () => {
  console.log('初始化用户:', userStore.user); // 调试：检查初始用户
  await Promise.all([fetchMaterials(), fetchUsers()]);
  await fetchInbounds();
});
</script>

<style scoped>
.material-inbound-manage {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.content {
  padding-top: 60px;
  width: 80%;
  margin: 0 auto;
  padding-bottom: 60px;
}

.operation-bar {
  margin: 20px 0;
}

.el-table {
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
</style>